//
//  OAuthVIewControllerViewController.swift
//  微博
//
//  Created by 吴思达 on 16/3/9.
//  Copyright © 2016年 吴思达. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthVIewControllerViewController: UIViewController {
    
    let webView = UIWebView()
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func defaultCount() {
        let isString = "document.getElementById('userId').value = '13599210787',document.getElementById('passwd').value = 'luckysida920818' "
        webView.stringByEvaluatingJavaScriptFromString(isString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        print("oauthr")
        setNavBar()
        
        loadOAuthPage()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultCount")
    }

 }

extension OAuthVIewControllerViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("request:")
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.containsString("code") {
            
            guard let query = request.URL?.query else {
                return false
            }
            let codeStr = "code="
            let cod = (query as NSString).substringFromIndex(codeStr.characters.count)
            UserAccount.shareAccount.loadAccessToken(cod, finished: { (isSucess) -> () in
                if !isSucess {
                    SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
                    return
                }
                self.close()
            })
        }
        return true
    }
}
